package com.amkai.aes.webservice.binary.objecthandler.diee;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.amkai.aes.aescommon.service.diee.DIEEReportPackageJob;
import com.amkai.aes.aescommon.service.diee.DIEEReportPackageResult;
import com.amkai.aes.aescommon.service.diee.InstallResultKind;
import com.amkai.aes.generatedbeans.conflict.ConflictSettingState;
import com.amkai.aes.generatedbeans.diee.ReportPackage;
import com.amkai.aes.generatedbeans.ui.validation.UiValidationMessage;
import com.amkai.aes.server.diee.DIEEServerUtils;
import com.amkai.common.extensions.hibernate.config.manager.SessionManager;
import com.amkai.diee.packages.DIEEReportPackageInstallRequest;
import com.amkai.diee.packages.InstallMethod;
import com.amkai.diee.packages.PackageHandlerServerSide;
import com.amkai.diee.utils.DIEEDebugger;
import com.amkai.diee.validation.ValidationData;
import com.amkai.diee.validation.ValidationManager;
import com.amkai.rad.designerbase.beans.ChangedKind;

public class DIEEReportPackageHandler extends AbstractDIEEHandler<DIEEReportPackageJob, DIEEReportPackageResult> {

	@Override
	protected DIEEReportPackageResult createResult() {
		return new DIEEReportPackageResult();
	}
	
	@Override
	protected String getName() {
		return "DIEE REPORT PACKAGE JOB";
	}
	
	@Override
	public void process(DIEEReportPackageJob job, Serializable object, DIEEReportPackageResult result, SessionManager sessionManager, DIEEDebugger debugger) throws Exception, Error {
		switch (job.getAction()) {
		case INSTALL:
			if (object!=null && (object instanceof DIEEReportPackageInstallRequest)) {
				DIEEReportPackageInstallRequest request = (DIEEReportPackageInstallRequest)object;
				info("Installing new package...");
				try {
					PackageHandlerServerSide handler = new PackageHandlerServerSide();
					handler.setMethod(job.isDevelopmentMode() ? InstallMethod.DEVELOPMENT : InstallMethod.PROTECTED);
					InstallResultKind resultKind = handler.install(sessionManager, request);
					result.addMessage(resultKind.toMessage(handler.getPackageName()));
					String details = resultKind.getDetails();
					if (details!=null) result.addMessage(details);
				} catch (Exception ex) {
					result.setException(ex);
					error("Error by installing a package!", ex);
				}
				// AES-18266
				queryPackages(result, sessionManager);
			} else {
				error("No package data to install!");
			}
			break;
		case UNINSTALL:
			if (job.getPackageNames()!=null && job.getPackageNames().length>0) {
				try {
					PackageHandlerServerSide handler = new PackageHandlerServerSide();
					handler.setMethod(job.isDevelopmentMode() ? InstallMethod.DEVELOPMENT : InstallMethod.PROTECTED);
					for (String packageName : job.getPackageNames()) {
						info("Uninstalling the package "+packageName+"...");
						InstallResultKind resultKind = handler.uninstall(sessionManager, packageName);
						result.addMessage(resultKind.toMessage(handler.getPackageName()));
						String details = resultKind.getDetails();
						if (details!=null) result.addMessage(details);
					}
				} catch (Exception ex) {
					result.setException(ex);
					error("Error by uninstalling a package!", ex);
				}
				queryPackages(result, sessionManager);
			} else {
				error("Package not specified!");
			}
			break;
		case QUERY:
			queryPackages(result, sessionManager);
			break;
		case VALIDATE:
			if (job.getPackageNames()!=null && job.getPackageNames().length>0) {
				info("Validationg the packages...");
				ValidationManager validator = new ValidationManager();
				ArrayList<UiValidationMessage> resultMessages = new ArrayList<UiValidationMessage>();
				List<ReportPackage> packages = sessionManager.execute(
						"select p from ReportPackage as p where p.name in (:names) order by p.name"
					).setParameterList("names", job.getPackageNames()).list();
				if (packages!=null) {
					for (ReportPackage p : packages) {
						p.setValid(true);
						List<UiValidationMessage> messages = validator.validate(new ValidationData<ReportPackage>(p));
						resultMessages.addAll(messages);
						for (UiValidationMessage msg : messages) {
							if (msg.getState()==ConflictSettingState.NOT_ALLOWED) {
								p.setValid(false);
								break;
							}
						}
						p.setChangedKind(ChangedKind.CHANGED);
						sessionManager.saveRADInTransaction(p);
					}
				}
				resultMessages.trimToSize();
				result.setValidationMessages(resultMessages);
				queryPackages(result, sessionManager);
			} else {
				error("Package not specified!");
			}
			break;
		}
	}
	
	private final void queryPackages(DIEEReportPackageResult result, SessionManager sessionManager) {
		info("Querying the packages...");
		List<ReportPackage> reportPackages = sessionManager.execute("from ReportPackage as p order by p.name").list();
		for (ReportPackage p : reportPackages) {
			DIEEServerUtils.initReportPackage(p);
			// reduce the net usage
			p.setReportDefinitions(null);
			p.setTaskXMLs(null);
			p.setReportTasks(null);
		}
		result.setReportPackages(reportPackages);
	}

}
